<!--
 * @Author: 王灿
 * @Date: 2019-11-25 00:32:05
 * @LastEditTime : 2020-01-04 00:13:43
 * @Description: 活动操作
 * @FilePath: \scarlet-sparrow-admin\src\views\commodity\commodity-activity\ActivityOperate\index.vue
 -->

<template>
  <div class="activity-operate">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
      <!-- 活动名称 -->
      <el-form-item prop="activityName">
        <el-input v-model="ruleForm.activityName" placeholder="活动名称" clearable></el-input>
      </el-form-item>
      <!-- 活动介绍 -->
      <el-form-item prop="introduce">
        <el-input v-model="ruleForm.introduce" placeholder="活动介绍" clearable></el-input>
      </el-form-item>
      <!-- 上传组件 活动主图 -->
      <el-form-item>
        <jq-upload :upData="mainPicObj" :fileList="fileList" @onChangeImageKey="onChangeImageKey" />
      </el-form-item>
      <!-- 活动商品 -->
      <el-form-item prop="productId">
        <el-select
          v-model="ruleForm.productId"
          filterable
          remote
          reserve-keyword
          clearable
          placeholder="请绑定商品"
          :remote-method="onGetCommodity"
        >
          <el-option
            v-for="item in productList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- sku -->
      <el-form-item prop="skuId">
        <el-select
          v-model="ruleForm.skuId"
          filterable
          remote
          reserve-keyword
          clearable
          placeholder="请绑定商品sku"
          :remote-method="onGetSkuList"
          @change="onChange"
        >
          <el-option
            v-for="item in skuList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 活动金额 -->
      <el-form-item prop="price">
        <el-input v-model="ruleForm.price" placeholder="活动金额" clearable></el-input>
      </el-form-item>
      <!-- 活动库存 -->
      <el-form-item prop="activityStock">
        <el-input v-model="ruleForm.activityStock" placeholder="活动库存" clearable></el-input>
      </el-form-item>
      <!-- 活动时间 -->
      <el-form-item>
        <jq-time :defaultValue="defaultValue" @onGetTime="onGetTime" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onSubmitForm('ruleForm')">确 定</el-button>
      <el-button @click="onCancelForm('ruleForm')">取 消</el-button>
    </div>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import JqUpload from '@/components/jq-upload/index.vue'
import JqTime from '@/components/jq-time/index.vue'
import {
  getProductList,
  getActivityAdd,
  getActivityUpdate,
  getSku
} from '@/api/commodity.js'
import { getDownUrl } from '@/api/commodity.js'
export default {
  name: 'ActivityOperate',
  components: { JqUpload, JqTime },
  props: {
    // 编辑默认数据
    row: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 请求数据标记
    isShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultValue: [],
      ruleForm: {
        id: '',
        price: '',
        productId: '',
        skuId: '',
        skuName: '',
        activityName: '',
        activityStock: '',
        startTime: '',
        endTime: '',
        introduce: '',
        mainPic: ''
      },
      productList: [],
      skuList: [],
      rules: {
        productId: [{ required: true, message: '请绑定商品', trigger: 'blur' }],
        price: [
          { required: true, message: '请输入活动价格', trigger: 'blur' },
          {
            pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
            message: '输入两位小数点',
            trigger: 'blur'
          }
        ],
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ],
        activityStock: [
          { required: true, message: '请输入活动库存', trigger: 'blur' },
          {
            pattern: /^[1-9]\d*$/,
            message: '库存必须为数字值',
            trigger: 'blur'
          }
        ]
      },
      fileList: [],
      // 活动主图
      mainPicObj: {
        label: '活动主图',
        accept: 'image/png, image/gif, image/jpg, image/jpeg',
        limit: 1,
        type: 1,
        isImage: true
      }
    }
  },
  watch: {
    // 监听数据变化
    row() {
      this.onGetDefaultData()
      this.onGetCommodity()
    },
    // 监听商品变化
    'ruleForm.productId'() {
      if (this.ruleForm.productId !== '') {
        this.onGetSkuList()
      }
    }
  },
  created() {
    this.onGetDefaultData()
    this.onGetCommodity()
  },
  methods: {
    // 获取所有商品
    onGetCommodity(query) {
      this.productList = []
      getProductList({
        name: query || ''
      }).then(res => {
        res.data.list.forEach(item => {
          let params = {}
          params.value = item.id
          params.label = item.name
          this.productList.push(params)
        })
      })
    },
    // 获取商品sku
    onGetSkuList(query) {
      if (this.ruleForm.productId !== '') {
        this.skuList = []
        getSku({
          productId: this.ruleForm.productId,
          tagName: query || ''
        }).then(res => {
          res.data.list.forEach(item => {
            let params = {}
            params.value = item.id
            params.label = item.tagName
            this.skuList.push(params)
          })
        })
      } else {
        if (this.isShow) {
           this.$message.error('请先选择商品')
        }
      }
    },
    // sku改变
    onChange(skuId) {
      this.skuList.forEach(item => {
        if (item.value === skuId) {
          this.ruleForm.skuName = item.label
        }
      })
    },
    // 默认数据
    onGetDefaultData() {
      this.defaultValue = []
      this.fileList = []
      let boolean = JSON.stringify(this.row) !== '{}'
      this.ruleForm = {
        id: boolean ? this.row.id : '',
        price: boolean ? this.row.price : '',
        productId: boolean ? this.row.productId : '',
        skuId: boolean ? this.row.skuId : '',
        skuName: boolean ? this.row.skuName : '',
        activityName: boolean ? this.row.activityName : '',
        activityStock: boolean ? this.row.activityStock : '',
        startTime: boolean ? this.row.startTime : '',
        endTime: boolean ? this.row.endTime : '',
        introduce: boolean ? this.row.introduce : '',
        mainPic: boolean ? this.row.mainPic : '',
      }
      if (boolean) {
        this.defaultValue = Array.of(
          dayjs(this.row.startTime).toDate(),
          dayjs(this.row.endTime).toDate()
        )
        if (this.isShow) {
          this.onGetCommodity(this.row.productName)
        }
        // 下载图片
        getDownUrl({
          fileName: this.row.mainPic
        }).then(res => {
          this.fileList.push({
            name: this.row.mainPic,
            url: res.data.url.split('?')[0]
          })
        })
      }
    },
    // 提交
    onSubmitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (!this.row.id) {
            this.onAdd()
          } else {
            this.onEdit()
          }
        }
      })
    },
    // 取消
    onCancelForm(formName) {
      this.$refs[formName].resetFields()
      let data = { isShow: false }
      this.$emit('onTableRow', data)
    },
    // 新增
    onAdd() {
      getActivityAdd(this.ruleForm).then(res => {
        this.$notify.success({
          title: '提示',
          message: '新增成功'
        })
        this.onRefresh()
      })
    },
    // 编辑
    onEdit() {
      getActivityUpdate(this.ruleForm).then(res => {
        this.$notify.success({
          title: '提示',
          message: '编辑成功'
        })
        this.onRefresh()
      })
    },
    // 刷新页面
    onRefresh() {
      setTimeout(() => {
        // TODO
        this.$emit('onChangeRefresh')
      }, 500)
    },
    // 获取时间
    onGetTime(data) {
      this.ruleForm.startTime = dayjs(data[0]).format('YYYY-MM-DD HH:mm:ss')
      this.ruleForm.endTime = dayjs(data[1]).format('YYYY-MM-DD HH:mm:ss')
    },
    // 子组件传值
    onChangeImageKey(fileName, type, isDetele, url) {
      this.ruleForm.mainPic = fileName
    }
  }
}
</script>
<style lang="scss" scoped>
.activity-operate {
  .el-form {
    margin-top: 30px;
    .el-form-item {
      margin-bottom: 22px;
      .el-input {
        &.el-input--suffix {
          margin-right: 0;
        }
      }
    }
  }
}
</style>
